/*
 * Created by Storm Zhang, Feb 11, 2014.
 */

package com.rio.volley;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.rio.core.U;

public abstract class GsonStringRequest<T> extends Request<T> {
	private final Listener<T> mListener;
	private Map<String, String> mHeaders;
	private Map<String, String> mParams;
	private String mContentType;
	private String mBoby;

	public GsonStringRequest(int method, String url,Map<String, String> headers,
			Listener<T> listener, ErrorListener errorListener) {
		super(method, url, errorListener);
		this.mHeaders = headers;
		this.mListener = listener;
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		if(mParams!=null)
			return mParams;
		return null;
	}
	
	/**
	 * 设置Body
	 * @param params
	 */
	public void setBody(Map<String, String> params) {
		mParams = params;
	}
	
	/**
	 * 设置Body
	 * @param params
	 */
	public void setBody(String params) {
		mBoby = params;
	}
	
	public void setHeaders(Map<String, String> headers) {
		mHeaders = headers;
	}
	
	public void setContentType(String type){
		mContentType = type;
	}
	
	@Override
	public byte[] getBody() throws AuthFailureError {
		if(U.notNull(mBoby))
			return mBoby.getBytes();
		return super.getBody();
	}
	
	@Override
	public String getBodyContentType() {
		if(U.notNull(mContentType)){
			return mContentType + "; charset="+getParamsEncoding();
		}
		return super.getBodyContentType();
	}
	
	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		return mHeaders != null ? mHeaders : super.getHeaders();
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		try {
			String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
			T result = executeResponse(json);
			return Response.success(result,HttpHeaderParser.parseCacheHeaders(response));
		} catch (Exception e) {
			return Response.error(new VolleyError(e));
		} 
	}

	public abstract T executeResponse(String json) throws Exception;

	@Override
	protected void deliverResponse(T response) {
		mListener.onResponse(response);	
	}
	
	
}
